<?php
namespace Components\Account\User\Wallet;

use Components\Account\User\Adapter;

class GoodsService {
  public const FIELD = 'goods';
  public const NAME = '货';

  public function sell($from_user_id, $amount, $remark = '') {
    if($amount <= 0) { return ['code' => -1, 'message' => '数量不能少于0']; }
    if(($amount % 100) != 0) { return ['code' => -1, 'message' => '卖出数量必须是100倍']; }

    $wallet = Adapter::getWalletServiceInstance() -> findFirst('user_id = ' . $from_user_id);
    if($wallet['code'] != 0) { return $wallet; }
    if($amount > $wallet['model'] -> {static::FIELD}) {
      return ['code'=>-1,'message'=>static::NAME.'数量不足'];
    }

    $transaction = (new \Phalcon\Mvc\Model\Transaction\Manager()) -> get();
    $currentTime = time();
    $walletLog = new Log\GoodsLogModel([
      'user_id' => $from_user_id,
      'from_user_id' => $from_user_id,
      'type' => 22,
      'active' => 0,
      'create_time' => $currentTime,
      'amount' => $amount,
      'amount_old' => $wallet['model'] -> {static::FIELD},
      'remark' => $remark . '-' . static::NAME . '卖出',
      'service_charge' => 0,
      'is_draw' => 1,
      'draw_time' => $currentTime
    ]);

		$walletSellLog = new Log\GoodsSellLogModel([
			'user_id' => $from_user_id,
			'create_time' => $currentTime,
			'amount' => $amount,
			'is_check' => 0,
			'check_time' => 0
		]);

    try {
      $wallet['model'] -> setTransaction($transaction);
      $wallet['model'] -> {static::FIELD} -= $amount;
      $walletLog -> amount_new = $wallet['model'] -> {static::FIELD};
      if(!$wallet['model'] -> save()) {
        $messages = $wallet['model'] -> getMessages();
        $transaction -> rollback($messages[0] -> getMessage());
      }

      $walletLog -> setTransaction($transaction);
			if(!$walletLog -> save()) {
				$messages = $walletLog -> getMessages();
				$transaction -> rollback($messages[0] -> getMessage());
			}

      $walletSellLog -> setTransaction($transaction);
			if(!$walletSellLog -> save()) {
				$messages = $walletSellLog -> getMessages();
				$transaction -> rollback($messages[0] -> getMessage());
			}

      $transaction -> commit();
    } catch(\Exception $e) {
      return ['code' => -1, 'message' => $e -> getMessage()];
    }

    return ['code' => 0, 'message' => static::NAME.'卖出成功,等待审核.'];
  }
}
